<?php
/**
 * Created by PhpStorm.
 * User: MSQ
 * Date: 2021/9/24
 * Time: 14:27
 */

namespace App\Utils;


use EasySwoole\EasySwoole\Config;
use EasySwoole\EasySwoole\ServerManager;

class WebSocketMessage
{
    const CheckTypeBy = 1;// 白友
    const CheckTypeScreen = 2;// 大屏

    const Error = 'error';
    const ErrorAuth = 'errorAuth';
    const Pong = 'pong';
    // 白友授权
    const ByAuthRes = 'byAuthRes';
    // 大屏授权
    const ScreenAuthRes = 'screenAuthRes';
    // 获取队列
    const QueueListByRes = 'queueListByRes';
    const QueueListScreenRes = 'queueListScreenRes';
    // 完成输液
    const QueueInfusionScreenRes = 'queueInfusionScreenRes';
    // 呼叫
    const QueueCallScreenRes = 'queueCallScreenRes';
    // 项目列表
    const ProjectListRes = 'projectListRes';
    // 刷新患者
    const PatientListByRes = 'patientListByRes';

    /**
     * 序列化包数据
     * @param string $msgType
     * @param $content
     * @return string
     */
    public static function getMessage(string $msgType, $content): string
    {
        $data = [
            'msgType' => $msgType,
            'content' => $content,
        ];

        return json_encode($data);
    }

    /**
     * 错误消息
     * @param $content
     * @return string
     */
    public static function getErrorMessage($content): string
    {
        return self::getMessage(self::Error, $content);
    }

    /**
     * 主动通知设备
     * @param int $fd
     * @param string $msgType
     * @param $content
     * @param array|null $resp
     */
    public static function sendToFd(int $fd, string $msgType, $content, int $checkType = 0)
    {
        $server = ServerManager::getInstance()->getSwooleServer();
        $clientInfo = $server->getClientInfo($fd);
        $data = self::getMessage($msgType, $content);

        if ($clientInfo && $clientInfo['server_port'] === Config::getInstance()->getConf("WEBSOCKET_SERVER.PORT")) {
            $isSend = 1;
            if ($checkType && in_array($checkType, [self::CheckTypeBy, self::CheckTypeScreen])) {
                $redisHelp = new RedisHelp();
                $fdInfo = $checkType == self::CheckTypeScreen
                    ? $redisHelp->getScreenFd($fd)
                    : $redisHelp->getByFd($fd);
                if (empty($fdInfo) || $fdInfo['check_type'] != $checkType) {
                    $isSend = 0;
                }
            }

            $isSend && $server->push($fd, $data);
        }/* else {
            LogHelp::error("fd: {$fd} data: {$data}", 'websocket');
        }*/
    }
}
